package com.xdhl.fu.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xdhl.fu.common.core.utils.DateUtils;
import com.xdhl.fu.common.core.utils.StringUtils;
import com.xdhl.fu.common.core.web.controller.BaseController;
import com.xdhl.fu.common.core.web.domain.AjaxResult;
import com.xdhl.fu.common.core.web.page.TableDataInfo;
import com.xdhl.fu.common.log.annotation.Log;
import com.xdhl.fu.common.log.enums.BusinessType;
import com.xdhl.fu.common.security.annotation.RequiresPermissions;
import com.xdhl.fu.flight.info.api.domain.FlightSchedule;
import com.xdhl.fu.flight.info.api.mongodb.domain.MGFlightSchedule;
import com.xdhl.fu.flight.info.api.mongodb.domain.MGReservation;
import com.xdhl.fu.order.domain.ChangeBody;
import com.xdhl.fu.order.domain.OrderInfo;
import com.xdhl.fu.order.domain.vo.OrderInfoVO;
import com.xdhl.fu.order.repository.MGFlightScheduleRepository;
import com.xdhl.fu.order.repository.MGReservationRepository;
import com.xdhl.fu.order.service.IOrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 订单改签控制层
 *
 * @author 朱力维
 * @time 2022/5/29 16:42
 */
@RestController
@RequestMapping("/change")
public class OrderChangeController extends BaseController {
    @Resource
    private IOrderInfoService orderInfoService;

    @Resource
    private MGFlightScheduleRepository mgFlightScheduleRepository;

    @Resource
    private MGReservationRepository mgReservationRepository;

    /**
     * 查询改签列表
     */
    @RequiresPermissions("order:change:list")
    @GetMapping("/list")
    public TableDataInfo list(OrderInfoVO orderInfoVO) {
        startPage();
        // 如果会员号不为空，则远程调用接口获取会员ID，并注入到条件值
        String memberDataId = "";
        if (null == memberDataId) {
            memberDataId = orderInfoVO.getMNumber();
        }
        LambdaQueryWrapper<OrderInfo> lqw = new LambdaQueryWrapper<>();
        // 只查询改签中的订单
        lqw.eq(true, OrderInfo::getChangeStatus, "B");
        lqw.eq(StringUtils.isNotBlank(memberDataId), OrderInfo::getMemberDataId, memberDataId);
        String fNumber = orderInfoVO.getFlightDataId();
        lqw.eq(StringUtils.isNotBlank(fNumber), OrderInfo::getFlightDataId, fNumber);
        List<OrderInfo> list = orderInfoService.list(lqw);
        long total = new PageInfo<>(list).getTotal();
        List<OrderInfoVO> infoVOS = new ArrayList<>();
        list.forEach(item -> {
            OrderInfoVO vo = new OrderInfoVO();
            BeanUtils.copyProperties(item, vo);
            vo.setMNumber("");
            infoVOS.add(vo);
        });

        return getDataTable(infoVOS, total);
    }

    /**
     * 同意改签申请
     */
    @RequiresPermissions("order:change:agree")
    @Log(title = "同意改签", businessType = BusinessType.UPDATE)
    @PutMapping("/agree")
    public AjaxResult agree(@RequestBody ChangeBody changeBody) {

        OrderInfo orderInfo = orderInfoService.getById(changeBody.getOrderDataId());
        orderInfo.setChangeDepartureTime(null);
        orderInfo.setChangeArrivalTime(null);
        orderInfo.setChangeClass(null);
        orderInfo.setChangePrice(null);
        orderInfo.setChangeTime(null);
        orderInfo.setRemark(null);
        orderInfo.setChangeStatus("C");
        orderInfoService.updateById(orderInfo);
        MGReservation reservation = mgReservationRepository.findById(orderInfo.getSerialNumber()).get();
        FlightSchedule flightSchedule = reservation.getFlightSchedule().getFlightSchedule();
        flightSchedule.setStartTime(changeBody.getStartTime());
        flightSchedule.setEndTime(changeBody.getEndTime());
        reservation.getFlightSchedule().setFlightSchedule(flightSchedule);
        reservation.setOrder(JSONObject.parseObject(JSONObject.toJSONString(orderInfo)));
        mgReservationRepository.save(reservation);
        return AjaxResult.success();
    }

    /**
     * 拒绝改签申请
     */
    @RequiresPermissions("order:change:refuse")
    @Log(title = "拒绝改签", businessType = BusinessType.UPDATE)
    @PutMapping("/refuse/{dataIds}")
    public AjaxResult refuse(@PathVariable String[] dataIds) {
        for (int i = 0; i < dataIds.length; i++) {
            OrderInfo orderInfo = orderInfoService.getById(dataIds[i]);
            orderInfo.setChangeDepartureTime(null);
            orderInfo.setChangeArrivalTime(null);
            orderInfo.setChangeClass(null);
            orderInfo.setChangePrice(null);
            orderInfo.setChangeTime(null);
            orderInfo.setChangeStatus("D");
            MGReservation reservation = mgReservationRepository.findById(orderInfo.getSerialNumber()).get();
            reservation.setOrder(JSONObject.parseObject(JSONObject.toJSONString(orderInfo)));
            mgReservationRepository.save(reservation);
            orderInfoService.updateById(orderInfo);
        }
        return toAjax(true);
    }

    /**
     * 会员申请改签
     */
    @PutMapping
    public AjaxResult change(@RequestBody ChangeBody changeBody) {
        // TODO 四折以下机票无法申请改期

        // 不可改期当天航班
        if (changeBody.getWhen().isEqual(LocalDate.now())) {
            return AjaxResult.error("不可改期当天航班");
        }
        MGFlightSchedule mgFlightSchedule = new MGFlightSchedule();
        mgFlightSchedule.setFlightNumber(changeBody.getFlightNumber());
        mgFlightSchedule.setStartStation(changeBody.getFrom());
        mgFlightSchedule.setEndStation(changeBody.getTo());
        mgFlightSchedule.setStartDate(changeBody.getWhen().format(DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD)));
        Example<MGFlightSchedule> example = Example.of(mgFlightSchedule, ExampleMatcher.matchingAll());
        Optional<MGFlightSchedule> one = mgFlightScheduleRepository.findOne(example);
        changeBody.setStartTime(one.get().getFlightSchedule().getStartTime());
        changeBody.setEndTime(one.get().getFlightSchedule().getEndTime());
        changeBody.setEconomySeatRemainderCount(one.get().getFlightStock().getEconomySeatRemainderCount());
        changeBody.setBusinessSeatRemainderCount(one.get().getFlightStock().getBusinessSeatRemainderCount());
        changeBody.setHeadSeatRemainderCount(one.get().getFlightStock().getHeadSeatRemainderCount());

        if (changeBody.getBusinessSeatRemainderCount() == 0 && changeBody.getHeadSeatRemainderCount() == 0 && changeBody.getEconomySeatRemainderCount() == 0) {
            return AjaxResult.error("当前航班已无余座");
        }
        if (orderInfoService.change(changeBody)) {
            return AjaxResult.success("改期申请成功，请等待管理员审核", null);
        }
        return AjaxResult.error("改期申请失败，请联系客服");
    }

}
